import sys
from .models import ListUser, Token


# 使用Token登录，无密码认证后端
class PasswordlessAuthenticationBackend:
    def authenticate(self, request, uid):
        print('uid', uid, file=sys.stderr)
        # 数据库中不存在该uuid返回None
        if not Token.objects.filter(uid=uid).exists():
            print('no token found', file=sys.stderr)
            return None
        token = Token.objects.get(uid=uid)
        print('got token', file=sys.stderr)
        try:
            user = ListUser.objects.get(email=token.email)
            print('got user', file=sys.stderr)
            return user
        except ListUser.DoesNotExist:
            # 用户不存在，创建新的用户
            print('new user', file=sys.stderr)
            return ListUser.objects.create(email=token.email)

    # 根据用户ID获取用户，模板中{{ user }}会调用该方法
    def get_user(self, pk):
        try:
            return ListUser.objects.get(pk=pk)
        except ListUser.DoesNotExist:
            return None
